package com.cas.configuration;

import com.cas.authentication.CustRememberMeUsernamePasswordCredential;
import com.cas.authentication.CustUsernamePasswordCredential;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.web.flow.CasWebflowConstants;
import org.apereo.cas.web.flow.configurer.DefaultWebflowConfigurer;
import org.springframework.context.ApplicationContext;
import org.springframework.webflow.definition.registry.FlowDefinitionRegistry;
import org.springframework.webflow.engine.Flow;
import org.springframework.webflow.engine.ViewState;
import org.springframework.webflow.engine.builder.BinderConfiguration;
import org.springframework.webflow.engine.builder.support.FlowBuilderServices;

/**
 * 参考 {@link org.apereo.cas.web.flow.configurer.DefaultWebflowConfigurer}
 */
public class CustDefaultWebflowConfigurer extends DefaultWebflowConfigurer {

    /**
     * Instantiates a new Default webflow configurer.
     *
     * @param flowBuilderServices    the flow builder services
     * @param flowDefinitionRegistry the flow definition registry
     * @param applicationContext     the application context
     * @param casProperties          the cas properties
     */
    public CustDefaultWebflowConfigurer(final FlowBuilderServices flowBuilderServices,
                                    final FlowDefinitionRegistry flowDefinitionRegistry,
                                    final ApplicationContext applicationContext,
                                    final CasConfigurationProperties casProperties) {
        super(flowBuilderServices, flowDefinitionRegistry, applicationContext, casProperties);
    }

    /**
     * 重写 {@link org.apereo.cas.web.flow.configurer.DefaultWebflowConfigurer} 的方法
     *
     * Create remember me authn webflow config.
     *
     * @param flow the flow
     */
    protected void createRememberMeAuthnWebflowConfig(final Flow flow) {
        //判断是否是启用rememberMe功能
        if (casProperties.getTicket().getTgt().getRememberMe().isEnabled()) {
            /**
             *用我们拓展CustUsernamePasswordCredential的CustRememberMeUsernamePasswordCredential来替换原来的
             * {@link org.apereo.cas.authentication.RememberMeUsernamePasswordCredential}
             */
            createFlowVariable(flow, CasWebflowConstants.VAR_ID_CREDENTIAL, CustRememberMeUsernamePasswordCredential.class);
            final ViewState state = getState(flow, CasWebflowConstants.STATE_ID_VIEW_LOGIN_FORM, ViewState.class);
            final BinderConfiguration cfg = getViewStateBinderConfiguration(state);
            cfg.addBinding(new BinderConfiguration.Binding("rememberMe", null, false));
        } else {
            /**
             *用我们拓展CustUsernamePasswordCredential来替换原来的
             * {@link org.apereo.cas.authentication.UsernamePasswordCredential}
             */
            createFlowVariable(flow, CasWebflowConstants.VAR_ID_CREDENTIAL, CustUsernamePasswordCredential.class);
        }
    }
}
